package com.example.xiaomi.Model.Service;
import com.example.xiaomi.Model.Controller.DaoList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


@WebServlet("/login")
public class login extends HttpServlet {
    DaoList dao = new DaoList();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String toggle = request.getParameter("toggle");
        request.setAttribute("toggle",toggle);
        request.getRequestDispatcher("/WEB-INF/Xiaomi/login.jsp").forward(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain;charset=utf-8");
        String arr = request.getParameter("arr");
        PrintWriter out = response.getWriter();
        if (arr!=null){
            String[] segmentation = arr.split(",");
            if (segmentation.length == 4){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String str = sdf.format(new Date());
                Long timestamp = null;
                try {
                    timestamp = sdf.parse(str).getTime() / 1000;
                    System.out.println(str);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int suffix = (int) Math.round((Math.random()+1) * 1000);
                String idstr = timestamp+suffix+"";


                int id = Integer.parseInt(idstr);
                String mail = segmentation[0];
                String password = segmentation[2];
                String avatar = "/Web_img/Xiaomi_default_avatar.jpg";
                //1 存在 2 注销
                int state = 1;
                String sex = "男";
                try {
                    dao.new_(id,mail,sex,avatar,mail,password,state);
                }catch (Exception e){
                    out.println("注册失败!");
                }
                request.getRequestDispatcher("/WEB-INF/Xiaomi/login.jsp").forward(request,response);
            }
        }
    }
}
